package com.github.cooingandwooing.uaa.validation;

import com.github.cooingandwooing.uaa.config.WebMvcConfig;
import com.github.cooingandwooing.uaa.util.CryptoUtil;
import lombok.RequiredArgsConstructor;
import lombok.val;
import org.passay.MessageResolver;
import org.passay.PasswordData;
import org.passay.PasswordValidator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @Description: 根据自定义规则校验密码，使用了 passay 密码库
 * @author cooingandwooing
 * @date 2022年5月31日
 */
@RequiredArgsConstructor
public class PasswordConstraintValidator implements ConstraintValidator<ValidPassword, String> {

    /**
     * 有一种 SpringMessageResolver 我们这里没有用
     * @see WebMvcConfig#messageResolver()
     */
    private final MessageResolver messageResolver;
    private final CryptoUtil cryptoUtil;

    @Override
    public void initialize(final ValidPassword constraintAnnotation) {
    }

    @Override
    public boolean isValid(final String password, final ConstraintValidatorContext context) {
        val validator = new PasswordValidator(messageResolver, cryptoUtil.getPasswordRules());
        val result = validator.validate(new PasswordData(password));
        if (result.isValid()) {
            return true;
        }
        // 禁止默认的校验约束
        context.disableDefaultConstraintViolation();
        // 根据自定义错误信息创建约束
        context.buildConstraintViolationWithTemplate(String.join(",", validator.getMessages(result)))
            .addConstraintViolation();
        return false;
    }
}
